package com.woniu.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

/**
 * Servlet Filter implementation class CharacterFilter
 */
@WebFilter(filterName = "CharacterFilter" ,initParams =  @WebInitParam(name = "encoding", value = "utf-8") ,urlPatterns = {"/*"} )
public class CharacterFilter implements Filter {
	private String encoding="";
    /**
     * Default constructor. 
     */
    public CharacterFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		//当一个变量不再被引用变量指向时才会被回收
		encoding = null;
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding(encoding);
		response.setContentType("text/html;charset=utf-8");
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		//利用FilterConfig读取配置参数
		encoding = fConfig.getInitParameter("encoding");
		if(encoding == null || encoding.trim().length() == 0 || !encoding.equalsIgnoreCase("utf-8")) {
			encoding="utf-8";
		}
		System.out.println("Filter init:\t"+encoding);
	}

}
